#include "nr_io_manager.h"
#include "nr_util.h"

#define NR_IOCONFIGS_FILE "\\io setting.xml"

nr_io_manager::nr_io_manager(void)
    : m_io(NULL)
{
}

nr_io_manager::~nr_io_manager(void)
{
}

nr_error_t nr_io_manager::load()
{
    // Load the io setting from the xml file
    nr_error_t ret = this->read_IOConfigs_FromXML();
    Q_ASSERT(ret == NR_ERROR_NONE);

    // use NR_IO_TYPE_MONGODB now.
    m_io = nr_io_factory::create( nr_io_factory::parse_IO_type(m_Type) );
    Q_ASSERT(m_io);
        
    // Connect to the database
    m_io->host() = m_Host;
//     m_io->port() = m_Port;
//     m_io->username() = m_Usernamne;
//     m_io->password() = m_Password;
    nr_error_t status = m_io->connect();
    return status;
}

nr_error_t nr_io_manager::unload()
{
    nr_io_factory::destroy(m_io);
    return NR_ERROR_NONE;
}

nr_error_t nr_io_manager::read_IOConfigs_FromXML()
{
    QString xml_path = nr_util::get_install_dir() + QString(NR_IOCONFIGS_FILE);
    QFile file(xml_path);
    if (!file.open(QIODevice::ReadOnly))
    {
        return NR_ERROR_OPEN_FILE_FAILED;
    }
    QString error_msg;
    int error_line = 0, error_column = 0; 
    QDomDocument doc;
    if (!doc.setContent(&file, &error_msg, &error_line, &error_column))
    {
        return NR_ERROR_PARSE_XML_FAILED;
    }

    QDomElement ioconfig_element = doc.namedItem("IOSetting").toElement();
    
    QDomNode node = ioconfig_element.firstChild();
    while ( !node.isNull() )
    {
        QDomElement element = node.toElement();
        if (element.tagName()=="Type")
        {
            m_Type = node.toElement().text();
        }
        else if (element.tagName()=="Host")
        {
            m_Host = node.toElement().text();
        }
        else if (element.tagName()=="Port")
        {
            m_Port = node.toElement().text();
        }
        else if (element.tagName()=="Usernamne")
        {
            m_Usernamne = node.toElement().text();
        }
        else if (element.tagName()=="Password")
        {
            m_Password = node.toElement().text();
        }

        node = node.nextSibling();
    }

    return NR_ERROR_NONE;
}